package servers

import (
	"github.com/gin-gonic/gin"
	"local/config"
	"local/databases/mysql"
	"local/models"
	"time"
)

// IndexLink 用户主页群组列表监听
func IndexLink(c *gin.Context) {
	userId := c.Param("userId")

	//用户首页群组列表
	indexList := []models.Group{}

	//升级get请求为webSocket协议
	ws, err := config.UpGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}

	//管道：用于传输群组列表数据
	indexChan := make(chan []models.Group)
	//开启协程，实时监听用户主页的群聊消息
	go func() {
		for {
			time.Sleep(time.Second * 1)
			//轮询数据库获取群组列表
			err := mysql.Db().Raw("select g.*,ug.look_num from im_group g,im_user_group ug where g.id=ug.group_id and ug.user_id=? and ug.status=1 order by g.update_time desc;", userId).Scan(&indexList).Error
			if err != nil {
				return
			}
			//发送数据到websocket协程
			indexChan <- indexList
		}
	}()
	defer ws.Close()
	for {
		//接数据库轮询协程的数据，写入websocket
		err = ws.WriteJSON(<-indexChan)
		if err != nil {
			break
		}
	}
}
